package thread_safe;

public class VolatileDemo {

    public static int race = 0;

    public static void increase() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        race++;
        System.out.println("race 的当前值为：" + race);
    }

    private static final int THREAD_COUNT = 20;

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[THREAD_COUNT];
        for (Thread thread : threads) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 100; i++) {
                        increase();
                    }
                }
            });
            thread.start();
//            thread.join(); //加上这个join就可以顺序输出了
        }
        while (Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println("race 的最终值为：" + race);
    }
}
